package com.itheima.health.job;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.health.constant.RedisConstant;
import com.itheima.health.utils.AliOssUtil;
import com.itheima.health.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Set;

/**
 * 任务类, 编写定时要执行的任务代码
 */
@Slf4j
public class ClearImgJob implements Job {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AliOssUtil aliOssUtil;

    // 编写定时要执行的任务代码
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("清除图片: " + LocalDateTime.now());
        // 根据Redis中保存的两个Set集合进行差值计算，获得垃圾图片名称

        Set<String> set = stringRedisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        System.out.println("需要清除的图片 = " + set);

        if (set != null) {
            for (String picName : set) {
                try {
                    String[] split = picName.split("/");
                    aliOssUtil.deleteImg(split[3]);
                } catch (ClientException e) {
                    throw new RuntimeException(e);
                }
                // 从Redis集合中删除图片名称
                stringRedisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES, picName);
            }
        }
    }
}